<?php 
$xmlDoc = new DOMDocument();
$xmlDoc->load("questions.xml");

$first = $xmlDoc->getElementsByTagName($_POST['first']);
$second = $xmlDoc->getElementsByTagName($_POST['second']);

srand(time());
$random = (rand()%$first->length);
$idx = (rand()%4);

$question = $first->item($random)->nodeValue; 
$answer = $first->item($random)->parentNode->getElementsByTagName($_POST['second'])->item(0)->nodeValue;

$i = 0;
while ( $i < 4 ) {
	if ( $i == $idx ) {
		$options[$i++] = $answer;
	} else {
		$random = (rand()%$second->length);	
		$option = $second->item($random)->nodeValue;
		if ( $option != $answer ) {
			$found = 0;
			for ( $j = 0; $j < sizeof($options); $j++ ) {
				if ( $options[$j] == $option ) {
					$found = 1;
					break;
				}	
			}
			if ( $found != 1 ) {
				$options[$i++] = $option;
			}
		}
	}
} 
?>
